import { defineStore } from 'pinia'
import cookies from './cookies'
import { treeToArray, jsonClone } from '../assets/js/utils'
import { getUserInfo } from "./api";
const modules = import.meta.glob("../pages/**/**.vue")

export const useStore = defineStore('main', {
  state: () => {
    return {
      hasRouters: false,
      userInfo: {} as any,
    }
  },
  getters: {},
  actions: {
    setLogin(token:string){
      cookies.setCookie('token',token);
      this.getUserInfo();
    },
    setLogout() {
      this.userInfo = {};
      cookies.clearCookie('token')
    },
    getUserInfo(force=false) {
      if(!this.userInfo.id || force){
        getUserInfo().then(res=>{
          Object.assign(this.userInfo,res);
        })
      }
    },
    generateRoutes(menuList:any) {
      return new Promise(resolve => {
        const hasHrefList = treeToArray(jsonClone(menuList)).filter((u: { href?: string; }) => u.href);
        const routerFromMenus = hasHrefList.map((item: { label: string; href: string, }) => {
          return {
            path: item.href,
            meta: { title: item.label },
            component: modules[`../pages${item.href}.vue`]
          }
        });
        this.hasRouters = true;
        resolve(routerFromMenus)
      })
    },
  }
})
